<template>
  <div class="divCheckListAdd box contenBox">
    <div class="divSteps">
      <el-steps :active="activeStep" finish-status="success">
        <el-step title="填写入库单基础信息"></el-step>
        <el-step title="填写货品清单"></el-step>
      </el-steps>
    </div>
    <div class="divForm" v-if="activeStep === 0">
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        v-loading="loading"
      >
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="入库单号" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入"
                clearable
                disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运单编号" prop="billCode">
              <el-input
                v-model="form.billCode"
                placeholder="请输入"
                clearable
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划到达时间" prop="planArrivalTime">
              <el-date-picker
                v-model="form.planArrivalTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                prefix-icon="el-icon-date"
                clearable
                style="width:100%"
                placeholder="选择日期时间"
                :picker-options="pickerOptions"
                >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货主" prop="ownerName">
              <el-autocomplete
                v-model="form.ownerName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入货主名称/编码"
                suffix-icon="el-icon-search"
                :trigger-on-focus="false"
                @select="handleSelect"
                @change="onOwnerChange"
                clearable
              >
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select placeholder="请选择仓库" v-model="form.warehouseId" style="width:100%" clearable @focus="warehouseFocus">
                <el-option v-for="item in warehouseData" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货人姓名" prop="shipperName">
              <el-input
                v-model="form.shipperName"
                placeholder="请输入"
                clearable
                maxlength="10"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="送货人姓名" prop="deliveryName">
              <el-input
                v-model="form.deliveryName"
                placeholder="请输入"
                clearable
                maxlength="10"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="送货人电话" prop="deliveryPhone">
              <el-input
                v-model="form.deliveryPhone"
                placeholder="请输入"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入"
                clearable
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="buttonBox" v-if="activeStep === 0">
      <base-button
        class="unimportanceButton"
        @click="btnReturnClick"
      >返回</base-button>
      <base-button
        class="minorImportantButton"
        @click="btnNextStepClick"
      >下一步</base-button>
    </div>
    <component-add-goods-detail v-if="activeStep > 0"  :masterId="masterId" :ownerId="form.ownerId"></component-add-goods-detail>
  </div>
</template>

<script lang="ts">
import BaseButton from '@/components/base-button/index.vue'
import { Component, Watch } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import SinglePage from '@/mixin/single-page'
import { ICommonReturn } from '@/utils/common-interface'
import { getAllOwner } from '@/module-business/api/owner'
import { IOwnerTableData } from '@/module-business/interface/owner'
import { generateWarehouseCode } from '@/api/common-api'
import { addWarehouseIn, findWarehouseIn, updateWarehouseIn } from '@/module-storage-in/api/warehouse-in'
import { ElForm } from 'element-ui/types/form'
import ComponentAddGoodsDetail from './components/component-add-goods-detail.vue'
import { validatePhone } from '@/utils/validate'
import { getAllWarehouse } from '@/module-base/api/warehouse'
@Component({
  name: 'StorageInAdd',
  components: {
    BaseButton,
    ComponentAddGoodsDetail
  }
})
export default class extends mixins(SinglePage) {
  private form = {
    code: '',
    billCode: '',
    planArrivalTime: '',
    ownerId: '', // 货主id
    ownerName: '', // 货主名称
    shipperName: '', // 待定
    deliveryName: '',
    deliveryPhone: null,
    remark: '',
    warehouseId: '',
    id: ''
  }

  private ownerOptions :IOwnerTableData[] = []

  private activeStep = 0// 2表示流程结束

  private loading = false

  private rules = {
    code: [{ required: true, message: '请输入入库单号', trigger: 'blur' }],
    billCode: [{ required: true, message: '请输入运单编号', trigger: 'blur' }],
    planArrivalTime: [{ required: true, message: '请选择计划到达时间', trigger: 'change' }],
    ownerName: [{ required: true, message: '请选择货主', trigger: 'change' }],
    shipperName: [{ required: true, message: '请输入发货人姓名', trigger: 'blur' }],
    deliveryName: [{ required: true, message: '请输入送货人姓名', trigger: 'blur' }],
    deliveryPhone: [
      { required: true, validator: validatePhone, trigger: 'blur' }],
    warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }]
  }

  private timeID ?:number= undefined

  private masterId = ''

  private warehouseData = []

  private pickerOptions = {
    disabledDate(time:Date) {
      return time.getTime() < Date.now()
    }
  }

  private map:Map<string, string> = new Map()

  private editFlag = false

  created() {
  // 只能写在这里，不然库区级联回显就会失败
    this.initData()
  }

  @Watch('form.ownerId', { immediate: true })
  private async onOwnerIdChange(ownerId:string) {
    if (this.editFlag) { // 编辑操作初始化防止清空仓库id
      this.editFlag = false
    } else {
      this.form.warehouseId = ''
    }
    if (ownerId) {
      const { data } = await getAllWarehouse({ status: 1, ownerId: ownerId })
      this.warehouseData = data
    } else {
      this.warehouseData = []
    }
  }

  private async initData() {
    const id = this.$route.params.id
    this.loading = true
    if (id === 'null') {
      // 新增
      Promise.all([getAllOwner(null), generateWarehouseCode('RK')])
        .then(res => {
          this.ownerOptions = res[0].data
          this.form.code = res[1].data
          this.loading = false
        })
    } else {
      this.masterId = id
      // 编辑
      Promise.all([getAllOwner(null), findWarehouseIn(id)])
        .then(res => {
          this.ownerOptions = res[0].data
          const data = res[1].data
          const ownerName = this.ownerOptions.filter(item =>
            item.id === data.ownerId
          )[0].name
          this.form = {
            ...data,
            ownerName
          }
          this.editFlag = true
          this.map.set(this.form.ownerId, this.form.ownerId)
          this.loading = false
        })
    }
  }

  private btnReturnClick() {
    this.$router.go(-1)
  }

  private btnNextStepClick() {
    (this.$refs.ruleForm as ElForm).validate(async(valid: boolean) => {
      if (valid) {
        const params = {
          ...this.form,
          ownerName: undefined,
          status: 1
        }
        let data: ICommonReturn
        if (!this.masterId) {
          // 新增操作
          data = ((await addWarehouseIn(params)) as unknown) as ICommonReturn
        } else {
          data = ((await updateWarehouseIn(params)) as unknown) as ICommonReturn
        }
        if (data.code === 0) {
          this.$message({
            showClose: true,
            message: '恭喜你，提交成功！',
            type: 'success'
          })
          this.activeStep = 1
          this.masterId = (data.data as any).id// 新增或者修改之后返回的记录的id
          this.form.id = (data.data as any).id
          this.map.set(this.form.ownerId, this.form.ownerId)
        } else {
          this.$message({
            showClose: true,
            message: data.msg,
            type: 'error'
          })
        }
      } else {
        return false
      }
    })
  }

  // 从填写盘点清单到填写基础信息
  private btnReturn() {
    this.activeStep = 0
  }

  private querySearchAsync(queryString:string, cb:Function) {
    const ownerOptions = this.ownerOptions
    const results = queryString ? ownerOptions.filter(this.createStateFilter(queryString)) : ownerOptions
    // 防抖
    clearTimeout(this.timeID)
    this.timeID = window.setTimeout(() => {
      cb(results.map((item:IOwnerTableData) => {
        return {
          value: item.name,
          id: item.id
        }
      }))
    }, 1000 * Math.random())
  }

  private createStateFilter(queryString:string) {
    return (state:IOwnerTableData) => {
      return ((state.name as any).toLowerCase().indexOf(queryString.toLowerCase()) > -1 ||
              (state.code as any).toLowerCase().indexOf(queryString.toLowerCase()) > -1
      )
    }
  }

  private handleSelect(item:any) {
    this.form.ownerId = item.id
  }

  private onOwnerChange(newValue:string) {
    if (!newValue) {
      this.form.ownerId = ''
    }
    if (!this.form.ownerId) {
      this.form.ownerName = ''
    }
  }

  private warehouseFocus() {
    if (!this.form.ownerId) {
      this.$message.error('请先选择货主')
    }
  }
}

</script>

<style lang="scss" scoped>
  .divCheckListAdd{
      .divSteps{
        width: 440px;
        margin: 0 auto;
        height: 100px;
        margin-top: 56px;
      }
  }
</style>
